package com.swift.violent.mainstay.security.feign;

import cn.hutool.core.util.StrUtil;
import com.swift.violent.mainstay.common.constants.CacheConstants;
import com.swift.violent.mainstay.common.util.ServletUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

/**
 * feign 请求拦截器
 *
 * @author ruoyi
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        final HttpServletRequest httpServletRequest = ServletUtil.getRequest();
        if (Objects.nonNull(httpServletRequest)) {
            final Map<String, String> headers =
                    ServletUtil.getHeaders(Objects.requireNonNull(httpServletRequest));
            final String userId = headers.get(CacheConstants.DETAILS_USER_ID);
            if (StrUtil.isNotEmpty(userId)) {
                requestTemplate.header(CacheConstants.DETAILS_USER_ID, userId);
            }
            final String userName = headers.get(CacheConstants.DETAILS_USERNAME);
            if (StrUtil.isNotEmpty(userName)) {
                requestTemplate.header(CacheConstants.DETAILS_USERNAME, userName);
            }
            final String authentication = headers.get(CacheConstants.AUTHORIZATION_HEADER);
            if (StrUtil.isNotEmpty(authentication)) {
                requestTemplate.header(CacheConstants.AUTHORIZATION_HEADER, authentication);
            }
        }
    }
}